import 'package:fluro/fluro.dart';
import 'package:flutter/services.dart';
import 'package:flutter_base_lib/flutter_base_lib.dart';

class BaseLibPlugin {
  BaseLibPlugin._();

  static const MethodChannel _channel = MethodChannel('baselib');

  static Future<String?> get platformVersion async {
    final String? version = await _channel.invokeMethod('getPlatformVersion');
    return version;
  }

  ///是否是debug模式
  static bool _isDebug = true;

  ///全局资源配置类
  static late IResConfig _resConfig;

  static bool get isDebug => _isDebug;

  static IResConfig get resConfig => _resConfig;

  ///初始化基础库,应用启动时调用
  ///[isDebug] 是否是debug模式
  ///[logConfig] 日志库配置
  ///[httpConfig] http相关配置信息
  ///[resConfig] 全局通用资源配置
  ///[buglyConfig] bugly相关配置信息，为null不使用bugly
  ///[toastImpl] Toast相关配置，为null使用默认Toast样式
  static Future<void> init({
    required bool isDebug,
    required LogConfig logConfig,
    required IHttpConfig httpConfig,
    required IResConfig resConfig,
    Function(FluroRouter route)? initRoute,
    String? wxAppId,
    BuglyConfig? buglyConfig,
    IToast? toastImpl,
  }) async {
    _isDebug = isDebug;
    _resConfig = resConfig;
    Constants.initPageIndex = _resConfig.configInitPageIndex();
    Constants.pageSize = _resConfig.configPageSize();

    ///初始化MMKV
    await MMKV.initialize();
    if (wxAppId != null && wxAppId.isNotEmpty) {
      await registerWxApi(appId: "wx931ca155d7e13abd");
    }

    ///初始化bugly
    if (buglyConfig != null) {
      await FlutterBugly.init(
        androidAppId: buglyConfig.androidAppId,
        iOSAppId: buglyConfig.iOSAppId,
        channel: buglyConfig.channel,
        autoCheckUpgrade: buglyConfig.autoCheckUpgrade,
        autoInit: buglyConfig.autoInit,
        autoDownloadOnWifi: buglyConfig.autoDownloadOnWifi,
        enableHotfix: buglyConfig.enableHotfix,
        enableNotification: buglyConfig.enableNotification,
        showInterruptedStrategy: buglyConfig.showInterruptedStrategy,
        canShowApkInfo: buglyConfig.canShowApkInfo,
        initDelay: buglyConfig.initDelay,
        upgradeCheckPeriod: buglyConfig.upgradeCheckPeriod,
        checkUpgradeCount: buglyConfig.checkUpgradeCount,
        customUpgrade: buglyConfig.customUpgrade,
      );
    }

    ///初始化日志库
    await M7Log.init(
        tag: logConfig.tag,
        isConsolePrintLog: logConfig.isConsolePrintLog,
        isUseFlutterPrintMethodLog: logConfig.isFlutterPrintLog,
        saveLogFilePath: logConfig.saveLogFilePath,
        encryptPubKey: logConfig.encryptPubKey);

    ///初始化Toast
    ToastUtil.init(toastImpl);

    ///初始化http组件
    M7Api.init(httpConfig);

    ///初始化路由
    final FluroRouter router = M7Route.configureRoutes();
    initRoute?.call(router);
  }

  ///应用关闭时调用该方法
  static Future<void> dispose() async {
    M7Log.dispose();
    FlutterBugly.dispose();
  }
}
